package com.hcj.demo.controller;

import com.hcj.demo.dto.ExpenseDto;
import com.hcj.demo.dto.LeaveDto;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 请假单 demoController
 */
@Slf4j
@RestController
@RequestMapping(value = "leave")
public class LeaveController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;


    /**
     * 添加请假单
     */
    @PostMapping("add")
    public String addLeave(@RequestBody LeaveDto leaveDto) {
        //启动流程
        BeanMap beanMap = BeanMap.create(leaveDto);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveRequest", beanMap);
        log.info("processInstance = {}", processInstance);
        return "提交成功.流程Id为：" + processInstance.getId();
    }


    /**
     * 审批请假单
     *
     * @param taskId 任务ID
     * @param isPass 0驳回1通过
     */
    @GetMapping("apply")
    public String apply(@RequestParam String taskId, @RequestParam(defaultValue = "1") Boolean isPass) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        log.info("task = {}", task);
        if (task == null) {
            throw new RuntimeException("请假单任务不存在");
        }
        //通过审核
        HashMap<String, Object> map = new HashMap<>();
        map.put("isPass", isPass);
        taskService.complete(taskId, map);
        return String.format("taskId=%s,审核结果： %s!", taskId, isPass);
    }


}
